package com.yangjiaying.kebiao.slice;

import com.yangjiaying.kebiao.ResourceTable;
import com.yangjiaying.kebiao.Utils.CookieUtlis;
import com.yangjiaying.kebiao.Utils.Log;
import com.yangjiaying.kebiao.config.Constant;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.FrameAnimationElement;
import ohos.agp.render.Canvas;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import okhttp3.*;
import okhttp3.internal.cache.DiskLruCache;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

public class loginPageSlice extends AbilitySlice implements Component.ClickedListener {

    /**
     * 登录按钮
     */
    private Button login;

    /**
     * 重置按钮
     */
    private Button reset;

    /**
     * 图片组件
     */
    private Image image;

    /**
     * 验证码图片
     */
    private Image verificationCodeImage;

    /**
     * 账号
     */
    private TextField accountText;

    /**
     * 密码
     */
    private TextField passwordText;

    /**
     * 验证码图片
     */
    private TextField verificationCodeText;

    /**
     * 记住账号密码
     */
    private Checkbox rememberCheckBox;

    private TaskDispatcher globalTaskDispatcher;

    static final HiLogLabel HI_LOG_LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00101, "MainAbility");


    private String cookie;//cookie


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_login_page);
        globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        initView();
        image.setCornerRadius(5);
        login.setClickedListener(this);
        reset.setClickedListener(this);
        verificationCodeImage.setClickedListener(this);
        ChangeImage();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            //登录事件
            case ResourceTable.Id_login:
                new ToastDialog(getContext()).setTitleText("提示").setContentText("提示内容:登录").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                System.out.println("账号:"+accountText.getText());
                System.out.println("密码:"+passwordText.getText());
                System.out.println("验证码:"+verificationCodeText.getText());
                LoginServer(accountText.getText(),passwordText.getText(),verificationCodeText.getText());
                Intent secondIntent = new Intent();
                // 指定待启动FA的bundleName和abilityName
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.yangjiaying.kebiao")
                        .withAbilityName("com.yangjiaying.kebiao.MainAbility")
                        .build();
                secondIntent.setOperation(operation);
                startAbility(secondIntent); // 通过AbilitySlice的startAbility接口实现启动另一个页面
                break;
            //重置事件
            case ResourceTable.Id_reset:
                new ToastDialog(getContext()).setTitleText("提示").setContentText("提示内容:重置").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                break;
            //点击图片刷新验证码
            case ResourceTable.Id_verificationCodeImage:
                ChangeImage();
                break;
        }
    }


    /**
     * 初始化控件
     */
    private void initView() {
        login = (Button) findComponentById(ResourceTable.Id_login);
        reset = (Button) findComponentById(ResourceTable.Id_reset);
        image = (Image) findComponentById(ResourceTable.Id_image);
        accountText = (TextField) findComponentById(ResourceTable.Id_account);
        passwordText = (TextField) findComponentById(ResourceTable.Id_password);
        verificationCodeImage = (Image) findComponentById(ResourceTable.Id_verificationCodeImage);
        verificationCodeText = (TextField) findComponentById(ResourceTable.Id_verificationCodeText);
        rememberCheckBox = (Checkbox) findComponentById(ResourceTable.Id_rememberCheckBox);
    }


    /**
     * 登录
     *
     * @param zhanghu
     * @param mima
     * @param yanzhengma
     */
    private void LoginServer(String zhanghu, String mima, String yanzhengma) {
        if (isNetworkAvailable(getContext())) {
            Constant.xuehao = zhanghu;
            OkHttpClient okHttpClient = new OkHttpClient();
            FormBody body = new FormBody.Builder()
                    .add("__VIEWSTATE", Constant.__VIEWSTATE)
                    .add("TextBox1", zhanghu)
                    .add("TextBox2", mima)
                    .add("TextBox3", yanzhengma)
                    .add("RadioButtonList1", "%D1%A7%C9%FA")
                    .add("Button1", "")
                    .build();

            if (rememberCheckBox.isChecked()) {
                DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
                String fileName = "kebiao"; // fileName表示文件名，其取值不能为空，也不能包含路径，默认存储目录可以通过context.getPreferencesDir()获取。
                System.out.println("存储路径:"+getContext().getPreferencesDir());
                Preferences preferences = databaseHelper.getPreferences(fileName);
                preferences.putString("use", zhanghu);
                preferences.putString("password", mima);
                preferences.putBoolean("gou", true);
                preferences.flush();
            } else {
                DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
                String fileName = "kebiao"; // fileName表示文件名，其取值不能为空，也不能包含路径，默认存储目录可以通过context.getPreferencesDir()获取。
                System.out.println("存储路径:"+getContext().getPreferencesDir());
                Preferences preferences = databaseHelper.getPreferences(fileName);
                preferences.putString("use", zhanghu);
                preferences.putString("password", mima);
                preferences.putBoolean("gou", false);
                preferences.flush();
            }

            System.out.println("cookie:"+cookie);
            final Request request = new Request.Builder()
                    .addHeader("cookie", cookie)
                    .url(Constant.jiaoyuanzhuyeURL)
                    .post(body)
                    .build();
            okhttp3.Call call2 = okHttpClient.newCall(request);
            call2.enqueue(new Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    e.printStackTrace();
                    LogRecord logRecord = new LogRecord(Level.INFO, "6");
                    handler.publish(logRecord);
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    /*你想要执行的下一步功能*/
                    byte[] bytes = response.body().bytes();
                    String data = new String(bytes, "gb2312");
                    Document document = Jsoup.parse(data);
                    String title = document.title();
                    System.out.println("html:"+data);
                    if ("登录".equals(title)) {
                        LogRecord logRecord = new LogRecord(Level.INFO, "7");
                        handler.publish(logRecord);
                    } else if ("ERROR - 出错啦！".equals(title)) {
                        LogRecord logRecord = new LogRecord(Level.INFO, "4");
                        handler.publish(logRecord);
                    } else if ("正方教务管理系统".equals(title)) {
//                        tiqu(data);
                    } else {
                        LogRecord logRecord = new LogRecord(Level.INFO, "4");
                        handler.publish(logRecord);
                    }
                }
            });
        } else {
            new ToastDialog(getContext()).setTitleText("提示").setContentText("没有网络!").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
        }

    }

    /**
     * 判断是否有网
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {

        return true;
    }


    /**
     * 得到Cookies和验证码图片
     */
    private void ChangeImage() {
        Request request = new Request.Builder()
                .url(Constant.jiaoyuanyanzhengmatuURL)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okhttp3.Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                LogRecord logRecord = new LogRecord(Level.INFO, "5");
                handler.publish(logRecord);
                System.out.println(e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                byte[] byte_image = response.body().bytes();
                InputStream sbs = new ByteArrayInputStream(byte_image);
                //渲染验证码
                renderThePicture(sbs);
//                bitmap = BitmapFactory.decodeByteArray(byte_image, 0, byte_image.length);//获取验证码图片
                Headers headers = response.headers();//获取网页头部
                List<String> cookies = headers.values("Set-Cookie");//取cookie值
                String session = cookies.get(0);
                String cookie1 = cookies.toString();
                Constant.__VIEWSTATE = CookieUtlis.getViewState(cookie1);//获取__VIEWSTATE
                cookie = session.substring(0, session.indexOf(";"));
                System.out.println("cookies:"+cookie);
                Constant.cookie = cookie;
            }
        });
    }

    /**
     * 渲染图片工具
     *
     * @param inputStream
     */
    private void renderThePicture(InputStream inputStream) {
        //创建图片源
        ImageSource imageSource = ImageSource.create(inputStream, null);
        //根据图片源创建位图
        PixelMap pixelMap = imageSource.createPixelmap(null);
        //需要异步渲染UI
        globalTaskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                //展示到组件上
                verificationCodeImage.setPixelMap(pixelMap);
                pixelMap.release();

            }
        });
    }


    /**
     * 1    给验证码控件附图片
     * 2    登陆成功并跳转
     * 3    提示出现不可预料的错误
     * 4    提示服务器验证失败,请稍后重试
     * 5    提示验证码获取失败
     * 6    提示服务器未响应，请稍后再试
     * 7    验证码输入错误时，提示并重新刷新验证码
     * 8    提示更新到最新版
     * 9    提示已经是最新版了
     */
    private Handler handler = new Handler() {
        @Override
        public void publish(LogRecord logRecord) {
            int message = Integer.parseInt(logRecord.getMessage());

            /*
             * 设置验证码图片
             * */
//            if (message == 1) {
//                yanzhengmatu.setImageBitmap(bitmap);
//            }
            /*
             * 登录成功跳转guodu界面
             * */
            if (message == 2) {

            }
            if (message == 3) {
                globalTaskDispatcher.asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setTitleText("提示").setContentText("出现不可预料的错误").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                    }
                });
            }

            if (message == 4) {
                globalTaskDispatcher.asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setTitleText("提示").setContentText("服务器验证失败,请稍后重试").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                    }
                });
            }

            if (message == 5) {
                globalTaskDispatcher.asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setTitleText("提示").setContentText("验证码获取失败").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                    }
                });
            }
            if (message == 6) {
                globalTaskDispatcher.asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setTitleText("提示").setContentText("服务器未响应，请稍后再试").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                    }
                });
            }
            if (message == 7) {
                globalTaskDispatcher.asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setTitleText("提示").setContentText("输入验证码错误").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                        ChangeImage();
                    }
                });
            }
            if (message == 8) {
                globalTaskDispatcher.asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setTitleText("提示").setContentText("请更新最新版").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                    }
                });
            }
            if (message == 9) {
                globalTaskDispatcher.asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        new ToastDialog(getContext()).setTitleText("提示").setContentText("当前版本为最新版").setAlignment(LayoutAlignment.CENTER).setDuration(5000).show();
                    }
                });
            }

        }

        @Override
        public void flush() {

        }

        @Override
        public void close() throws SecurityException {

        }


    };

}
